# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>
from excavator.job.base import Job
# harvests
from excavator.job.harvests_efi import *
from excavator.job.harvests_firewalld import *
from excavator.job.harvests_network import *
from excavator.job.harvests_openssh import *
from excavator.job.harvests_pkg import *
from excavator.job.harvests_selinux import *

# prepare
from excavator.job.prepare_download import *
# from excavator.job.prepare_efi import *
from excavator.job.prepare_reboot import *
from excavator.job.prepare_rpmdbpath import *
from excavator.job.prepare_release import *
from excavator.job.prepare_rpmsubject import *

# check
from excavator.job.check_cpu import *
# from excavator.job.check_pkg import *
from excavator.job.check_release import *
from excavator.job.check_update import *

# boot
from excavator.job.boot_config import *
from excavator.job.boot_coreservice import *
from excavator.job.boot_dbus import *
# from excavator.job.boot_efi import *
from excavator.job.boot_firewalld import *
from excavator.job.boot_grub import *
from excavator.job.boot_nginx import *
from excavator.job.boot_openssh import *
from excavator.job.boot_rebuildrpmdb import *
from excavator.job.boot_upgradepkg import *

from excavator.utils.subclasses import get_all_subclasses


def sort_jobs(jobs):
    infos = {}
    for job in jobs:
        for info in job.provides:
            infos.setdefault(info.__name__, {'provides': []})['provides'].append(job)

    new_jobs, jobs = jobs, []
    while new_jobs:
        scheduled = []
        for idx, job in enumerate(new_jobs):
            for info in job.requires:
                if infos[info.__name__]['provides']:
                    break
            else:

                for info in job.provides:
                    infos[info.__name__]['provides'].remove(job)

                scheduled.append(idx)
                jobs.append(job)

        if not scheduled:
            raise Exception(
                "Could not solve dependency order for '{}'".format(', '.join([job.name for job in new_jobs])))

        for idx in reversed(scheduled):
            new_jobs.pop(idx)

    return jobs


def get_group_jobs(group):
    all_jobs = get_all_subclasses(Job)
    group_jobs = []
    for job in all_jobs:
        if group == job.group:
            group_jobs.append(job)
    return group_jobs


def get_all_jobs():
    return get_all_subclasses(Job)
